--
-- Author: ping.wang
-- Date: 2019-02-28 15:25:41
--
-- PvpDuelPanel
--

local ClassRef = app.mvc.createPanelClass(...)
local PvpDuelLeftPanel = import(".PvpDuelLeftPanel")
local PvpDuelPlayerPanel = import(".PvpDuelPlayerPanel")
local IconRender = require("app.widget.renders.IconRender")
local AvatarIconNode = require("app.widget.AvatarIconNode")
local string_split = string.split
local table_insert = table.insert

local duelGreen = cc.c3b(156,255,0)
local duelBlue = cc.c3b(21,188,255)
local duelOrange = cc.c3b(255,192,0)
--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.PvpDuelNode))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)
    self:setContentSize( self._ui.Panel:getContentSize() )
    self._selectedIdx = 1
    self._vsPanel = self._ui.Panel_vs
    self._enemyHeadIcon = AvatarIconNode.new(self._vsPanel:findChild("icon_4"), "icon_img")
    self._myHeadIcon = AvatarIconNode.new(self._vsPanel:findChild("icon_1"), "icon_img")

    for i = 1, 2 do
        local j = i+1
        local icon = self._vsPanel:findChild("icon_"..j)
        local btn = self._vsPanel:findChild("btn_"..j)
        icon:setTouchEnabled(true)
        btn:setTouchEnabled(true)

        icon:addClickEventListener(function()
            if self._data and self._data.myInfo then
                local partnerVo = self._data.myInfo:getPartnerInfos()[i]
                if partnerVo then
                    self:_showPopWin(icon,i, partnerVo.id)
                end
            end

        end) --显示弹窗 踢出随从 和 切换随从两个按钮
        btn:addClickEventListener(function()
            self:_showChangePartnerWin(i)
        end)

    end

    self._leftPanel = PvpDuelLeftPanel.create(self._ui.left)
    self._leftPanel:onOperate(function(op, data)
        executeFunc(self._onOperate, op, data)
    end)
    self._ui.Panel_vs:setLocalZOrder(2)

    self._opponentPanels = {}
    for i = 1, 3 do
        local playerPanel = PvpDuelPlayerPanel.create(self._ui.Panel:findChild("player0"..i))
        playerPanel:setIdx(i)
        playerPanel:onOperate(function(op, data)
            if op == "selectDuelOpponent" then
               self:setSelectedIdx(data, false)
            else
                executeFunc(self._onOperate, op, data)
            end
        end)
        table_insert(self._opponentPanels, playerPanel)
    end

    self._randAwardIcons = {}
    for i = 1, 5 do
        local awardIcon = IconRender.create(self._ui.Panel_icon:findChild("icon"..i))
        table_insert(self._randAwardIcons ,awardIcon)
        awardIcon:setTipEnable(true)
    end

    self._rankAwardData =  UD:parseRewardToBagItem(GD:getSystemStrPar("duelGameRankingReward"))

    self._fightNumText = self._ui.Panel_num:findChild("num")
    --左侧我的信息

    --每次添加需要消耗的钻石
    local costDaibi = UD:parseRewardToBagItem(GD:getSystemStrPar("duelGamePlayPrice"))
    self._ui.Panel_num:findChild("btn_add"):addClickEventListener(function()
        --打开添加次数的界面
        local confirmDialog = display.newConfirmDialog(string.format(L("duelGametips33"),costDaibi:getAmount()),
            function() -- 确定
                executeFunc(self._onOperate, "buyDuelFightNum")
            end)
        UIHandler:addPopDialog( confirmDialog )
    end)
    self._ui.Panel_num:setTouchEnabled(true)
    self._ui.Panel_num:addClickEventListener(function()
        --打开添加次数的界面
        local confirmDialog = display.newConfirmDialog(string.format(L("duelGametips33"),costDaibi:getAmount()),
            function() -- 确定
                executeFunc(self._onOperate, "buyDuelFightNum")
            end)
        UIHandler:addPopDialog( confirmDialog )
    end)

    self._ui.Button_enter:addClickEventListener(function()
        --先判断是否调整过随从
        local haveChangePartner = UD:getValueFromGenericByKey("duelChangePartner")
        if haveChangePartner then
            --如果调整过随从
            self:_sendStartDuelFight()
        else
            --没有调整过
            UD:saveGeneric("duelChangePartner",true)
            local confirmDialog = display.newConfirmDialog(L("duelGametips34"),
                function() -- 确定
                    executeFunc(self._onOperate, "openDuelTeamView")
                end,
            function() --取消
                self:_sendStartDuelFight()
            end)
            UIHandler:addPopDialog( confirmDialog )
        end

    end)

    self:refresh()
end

function ClassRef:_sendStartDuelFight()
    --判断剩余次数是否足够
    if self._data then
        if self._data.myInfo:getRemainingTimes() > 0 then
            executeFunc(self._onOperate, "startDuelFight", self._selectedIdx)
        else
            local costDaibi = UD:parseRewardToBagItem(GD:getSystemStrPar("duelGamePlayPrice"))
            local confirmDialog = display.newConfirmDialog(string.format(L("duelGametips35"),costDaibi:getAmount()),
                function() -- 确定
                    executeFunc(self._onOperate, "buyDuelFightNum")
                end)
            UIHandler:addPopDialog( confirmDialog )
        end
    end
end


function ClassRef:setSelectedIdx(idx, forceRefresh)
    if not self._data or not self._data.enemyList then
        return
    end

    if not forceRefresh and self._selectedIdx == idx then
        return
    end
    self._selectedIdx = idx

    for i = 1, 3 do
        self._opponentPanels[i]:setSelectedState(idx == i)
    end

    --选中后替换vs界面的icon
    local enemyInfo = self._data.enemyList[idx]
    if enemyInfo then
        local enemyUdbInfo = enemyInfo:getUserDataBaseInfo()
        self._enemyHeadIcon:update(enemyUdbInfo)
        local partnerInfos = enemyInfo:getPartnerInfos()
        for i = 1, 2 do
            local j = i+4
            local icon = self._vsPanel:findChild("icon_"..j)
            if i > #partnerInfos then
                icon:setVisible(false)
            else
                icon:setVisible(true)

                local partnerInfo = partnerInfos[i]
                --这里要设置随从的icon
                if Res.Quality_Partner_Icon[partnerInfo.quality] then
                    icon:loadTexture(Res.Quality_Partner_Icon[partnerInfo.quality])
                end

                local partnerCfg = GD:queryPartnerById( partnerInfo.id )
                if partnerCfg then
                    icon:findChild("icon_img"):loadTexture(GD:getImagePath(Res.partnerIconPath,partnerCfg.icon))
                end
            end
        end
        --战斗力需要计算随从 稍后计算
        local powerNum = tonumber(enemyInfo:getTeamCombatPower())
        self._vsPanel:findChild("text_2"):setString(string.format(L("duelGametips11"),powerNum))

        local startIdx = self._data.myInfo:getHighestRanking()
        local endIdx = enemyInfo:getRankNum()

        for i = 1, #self._randAwardIcons do
            self._randAwardIcons[i]:setVisible(false)
            self._ui.Panel_icon:findChild("Text_"..i):setVisible(false)
        end



        local awardNum = 0
        if startIdx > endIdx then
            awardNum = GD:getDuelRankAwardInfo(startIdx, endIdx)
            if awardNum > 0 then
                self._rankAwardData:setAmount(awardNum)
                self._randAwardIcons[1]:setData(self._rankAwardData)
                self._randAwardIcons[1]:setVisible(true)
                local text = self._ui.Panel_icon:findChild("Text_1")
                text:setVisible(true)
                text:setString(L("duelGametips15"))
                text:setTextColor(duelOrange)
            end
        end

        local startIdx = 0

        if awardNum > 0 then
            startIdx = 1
        end

        --奖励面板 前面2个是固定的
        local awardDatas = string_split(GD:getSystemStrPar("duelGameWinReward"),";")
        local awardIdx = startIdx
        for i = 1, #awardDatas do
            awardIdx = i + startIdx
            if awardIdx <= #self._randAwardIcons then
                local awardData = UD:parseRewardToBagItem(awardDatas[i])
                local award1 = self._randAwardIcons[awardIdx]
                award1:setData(awardData)
                award1:setVisible(true)

                local text = self._ui.Panel_icon:findChild("Text_"..awardIdx)
                text:setVisible(true)
                text:setString(L("duelGametips13"))
                text:setTextColor(duelGreen)
            end
        end

        awardIdx = startIdx + #awardDatas + 1
        if awardIdx <= #self._randAwardIcons then
            local awardData2 =  UD:parseRewardToBagItem(GD:getSystemStrPar("duelGameLoseReward"))
            local award2 = self._randAwardIcons[awardIdx]
            award2:setData(awardData2)
            award2:setVisible(true)

            local text = self._ui.Panel_icon:findChild("Text_"..awardIdx)
            text:setVisible(true)
            text:setString(L("duelGametips14"))
            text:setTextColor(duelBlue)
        end

    end
end

--根据数据刷新挑战次数
function ClassRef:_setFightNumText(num)
    self._fightNumText:setString(tostring(num))
end

--显示一个弹窗 穿线踢出随从 和 切换随从两个按钮
function ClassRef:_showPopWin(icon, i, partnerUID)
    local pos = self._vsPanel:convertToWorldSpace( icon:getPosition() )
    pos.x = pos.x + 30
    UIHandler:showHeadMenu( {idx = i, pos = pos,type = Enums.MenuType.duel, partnerId = partnerUID} )
end

--显示切换随从界面
function ClassRef:_showChangePartnerWin()
    executeFunc(self._onOperate, "openDuelTeamView")
end

--{myInfo = duelMyInfo, enemyList = opponentInfos}
function ClassRef:refresh()
    if self._data then
        self:setVisible( true )
        --dump(self._data.enemyList)
        local data = self._data
        for k,v in ipairs(self._opponentPanels) do
            if k <= #data.enemyList then
                v:setData(data.enemyList[k])
            end
        end

        self:setSelectedIdx(self._selectedIdx, true)
        --vs界面我方信息可以确定了
        self:_setMyVsPanelInfo(data.myInfo)
        --刷新次数
        self:_setFightNumText(data.myInfo:getRemainingTimes())
        --左侧面板
        self._leftPanel:setData(data.myInfo)
    else
        self:setVisible( false )
    end
end

--PvpDuelMemberVo
function ClassRef:_setMyVsPanelInfo(myVsInfo)
    local myUdbInfo = myVsInfo:getUserDataBaseInfo()
    self._myHeadIcon:update(myUdbInfo)

    local partnerInfos = myVsInfo:getPartnerInfos()
    for i = 1, 2 do
        local j = i+1
        local icon = self._vsPanel:findChild("icon_"..j)
        if i > #partnerInfos then
            icon:setVisible(false)
            self._vsPanel:findChild("btn_"..j):setVisible(true)
        else
            icon:setVisible(true)
            self._vsPanel:findChild("btn_"..j):setVisible(false)
            local partnerInfo = partnerInfos[i]
            --这里要设置随从的icon
            if Res.Quality_Partner_Icon[partnerInfo.quality] then
                icon:loadTexture(Res.Quality_Partner_Icon[partnerInfo.quality])
            end

            local partnerCfg = GD:queryPartnerById( partnerInfo.id )
            if partnerCfg then
                icon:findChild("icon_img"):loadTexture(GD:getImagePath(Res.partnerIconPath, partnerCfg.icon))
            end
        end
    end

    --我的战斗力描述
    local powerNum = tonumber(myVsInfo:getTeamCombatPower())
    self._vsPanel:findChild("text_1"):setString(string.format(L("duelGametips11"),powerNum))
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

return ClassRef
